#include "mystdio.h"
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>

MyFile *BuyMyFile(int fd, int flag)
{
    MyFile *fp = (MyFile*)malloc(sizeof(MyFile));
    if(!fp) return NULL;
    fp->fileno = fd;
    fp->bufferlen = 0;
    fp->flag = flag;
    fp->flush_method = LINE_FLUSH;
    memset(fp->outbuffer,0,sizeof(fp->outbuffer));
    return fp;
}
//方法
MyFile *MyFopen(const char *path, const char *mode)
{
    int flag = 0;
    int fd = -1;
    if(strcmp(mode,"w"))
    {
        flag = O_CREAT|O_WRONLY|O_TRUNC;
        fd = open(path, flag, 0666);
    }
    else if(strcmp(mode,"a"))
    {
        flag = O_CREAT|O_WRONLY|O_APPEND;
        fd = open(path, flag, 0666);
    }
    else if(strcmp(mode,"r"))
    {
        flag = O_RDONLY;
        fd = open(path, flag, 0666);
    }
    else
    {
        //...
    }
    if(fd < 0) return NULL;
    MyFile *fp = BuyMyFile(fd, flag);
    if(!fp) return NULL;
    return fp;
}

int MyFwrite(const void *ptr, int len, MyFile *fp)
{
    //不考虑其它
    //拷贝
    memcpy(fp->outbuffer+fp->bufferlen, ptr, len);
    //检查行缓冲
    fp->bufferlen += len;
    if(fp->outbuffer[fp->bufferlen-1]=='\n')
        MyFlush(fp);

    return len;
}

void MyFclose(MyFile *fp)
{
    if(fp->fileno<0)return;
    MyFlush(fp);

    close(fp->fileno);

    free(fp);
}

void MyFlush(MyFile *fp)
{
    if(fp->bufferlen<=0)return;
    //负责写入到内核文件缓冲区即可
    int n = write(fp->fileno, fp->outbuffer, fp->bufferlen);
    (void)n;
    fp->bufferlen = 0;
    //也可以直接刷新内核文件缓冲区
    fsync(fp->fileno);
}

